# coding: utf-8
import os
import requests
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import uuid

from NewStudentManageSys.settings.dev import MEDIA_ROOT


class ImageProcessing():
    @staticmethod
    def process_three(base_img_url, data):
        """
        :param base_img_url: 报告背景图片
        :param head_img_url: 用户微信头像远程访问地址
        :return: 报告结果保存在服务器上的地址
        """
        if not os.path.exists(base_img_url):
            raise Exception('底图不存在')
        image = Image.open(base_img_url)
        # font_path = r'/workspace/hu_dirs/previson-acdamic/media/HKB.TTF'
        font1 = ImageFont.truetype(r'media/word/SourceHanSansCN-Bold.otf', 28)
        font2 = ImageFont.truetype(r'media/word/SourceHanSansCN-Normal.otf', 24)
        font3 = ImageFont.truetype(r'media/word/SourceHanSansCN-Medium.otf', 22)
        draw = ImageDraw.Draw(image)
        # # 昵称位置
        draw.text((154, 375), f"{data['name']}", fill=(230, 30, 43), font=font1, align='left')
        draw.text((60, 535), f"{data['project_name']}", fill=(31, 31, 31), font=font2, align='left')
        draw.text((172, 633), f"{data['start_date']}", fill=(31, 31, 31), font=font2, align='left')
        draw.text((349, 633), f"{data['end_date']}", fill=(31, 31, 31), font=font2, align='left')
        draw.text((321, 683), f"{data['start_date']}", fill=(31, 31, 31), font=font2, align='left')
        i = 1
        j = 0
        for course in data['course']:
            string = str(i)+'.'+f"{course['project_course__course_code']}" + ' ' + f"{course['project_course__e_course_name']}"
            if len(string) > 50:
                string = string[0:50] + '-\n' + string[50:-1]
                draw.text((60, 856 + (i + j) * 30), string, fill=(31, 31, 31), font=font3, align='left')
                j += 1
            else:
                draw.text((60, 856+(i + j)*30), string, fill=(31, 31, 31), font=font3, align='left')
            i += 1
        draw.text((80, 1463), f"{data['server_name']}", fill=(255, 255, 255), font=font2, align='left')
        # 对远程获取的头像进行处理
        # if not head_img_url:
        #     head_img_url = 'https://solution-qiniu.brilianclass.com/moren1f6601d498a54471a14954f52ec66bbd.png'
        # head_res = requests.get(data['qr_code'], verify=False)
        # local_head_image = Image.open(BytesIO(head_res.content))
        # qr_res = requests.get(data['qr_code'], verify=False)
        requests.packages.urllib3.disable_warnings()
        qr_res = requests.get('https://students-system-v3.lxhelper.com/png.png', verify=False)
        # qr_res = requests.get('http://students-system-v3.lxhelper.com/1596444770567.png', verify=False)
        local_qr_image = Image.open(BytesIO(qr_res.content))
        # local_head_image.thumbnail((2000,200))
        relative_path = 'starcourse' + '.png'
        # MEDIA_ROOT = r'temp_images'
        # width, hight = local_head_image.size
        # 图片大小
        # local_head_image = local_head_image.resize((104, 104))
        local_qr_image = local_qr_image.resize((140, 171))
        # 头像位置
        result_one = ImageProcessing.draw_rectangle_avatar(local_qr_image, image, (565, 1365))
        # result = ImageProcessing.draw_circle_avatar(local_head_image, result_one, (84, 404))
        image_save_url = os.path.abspath(os.path.join(MEDIA_ROOT, relative_path))
        result_one.save(image_save_url)
        return image_save_url

    @staticmethod
    def process_four(base_img_url, name, start_date, end_date):
        """
        :param base_img_url: 报告背景图片
        :param head_img_url: 用户微信头像远程访问地址
        :return: 报告结果保存在服务器上的地址
        """
        if not os.path.exists(base_img_url):
            raise Exception('底图不存在')
        image = Image.open(base_img_url)
        # font_path = r'/workspace/hu_dirs/previson-acdamic/media/HKB.TTF'
        # font_path = r'images/HKB.TTF'
        # font1 = ImageFont.truetype("images/SourceHanSansCN-Bold.otf", 28)
        # font2 = ImageFont.truetype(font_path, 28)
        # draw = ImageDraw.Draw(image)
        # # 昵称位置
        # (width, height) = font1.getsize(nickname)
        # draw.text((206, 163), f"{nickname}", fill=(255, 255, 255), font=font1, align='left')
        # draw.text((206 + width, 163), "邀请你使用", fill=(255, 255, 255), font=font2, align='left')
        # 对远程获取的头像进行处理
        head_res = requests.get(head_img_url, verify=False)
        local_head_image = Image.open(BytesIO(head_res.content))

        qr_res = requests.get(qr_img_url, verify=False)
        local_qr_image = Image.open(BytesIO(qr_res.content))
        # local_head_image.thumbnail((2000,200))
        relative_path = str(uuid.uuid4()) + '.png'
        MEDIA_ROOT = r'images'
        # width, hight = local_head_image.size
        # 图片大小
        local_head_image = local_head_image.resize((104, 104))
        local_qr_image = local_qr_image.resize((142, 142))
        # 头像位置
        result_one = ImageProcessing.draw_rectangle_avatar(local_qr_image, image, (530, 682))
        result = ImageProcessing.draw_circle_avatar(local_head_image, result_one, (74, 768))
        image_save_url = os.path.abspath(os.path.join(MEDIA_ROOT, relative_path))
        result.save(image_save_url)
        return image_save_url

    @staticmethod
    def process_two(base_img_url, qr_img_url,head_img_url,nickname):
        """
        :param base_img_url: 报告背景图片
        :param head_img_url: 用户微信头像远程访问地址
        :return: 报告结果保存在服务器上的地址
        """
        if not os.path.exists(base_img_url):
            raise Exception('底图不存在')
        image = Image.open(base_img_url)
        # font_path = r'/workspace/hu_dirs/previson-acdamic/media/HKB.TTF'
        font_path = r'images/HKB.TTF'
        font1 = ImageFont.truetype("images/SourceHanSansCN-Bold.otf", 28)
        font2 = ImageFont.truetype(font_path, 28)
        draw = ImageDraw.Draw(image)
        # 昵称位置
        (width, height) = font1.getsize(nickname)
        draw.text((206, 163), f"{nickname}", fill=(255, 255, 255), font=font1, align='left')
        draw.text((206+width, 163), "邀请你使用", fill=(255, 255, 255), font=font2, align='left')
        # 对远程获取的头像进行处理
        head_res = requests.get(head_img_url, verify=False)
        local_head_image = Image.open(BytesIO(head_res.content))

        qr_res = requests.get(qr_img_url, verify=False)
        local_qr_image = Image.open(BytesIO(qr_res.content))
        # local_head_image.thumbnail((2000,200))
        relative_path = str(uuid.uuid4()) + '.jpg'
        MEDIA_ROOT = r'temp_images'
        # width, hight = local_head_image.size
        # 图片大小
        local_head_image = local_head_image.resize((100, 100))
        local_qr_image = local_qr_image.resize((132, 132))
        # 头像位置
        result_one = ImageProcessing.draw_rectangle_avatar(local_qr_image, image, (40, 1180))
        result = ImageProcessing.draw_circle_avatar(local_head_image, result_one, (86, 144))
        image_save_url = os.path.abspath(os.path.join(MEDIA_ROOT, relative_path))
        result.save(image_save_url)
        return image_save_url

    @staticmethod
    def process_one(base_img_url, head_img_url, nickname, code):
        """
        生成分享图片（不带二维码）
        :param base_img_url: 报告背景图片
        :param head_img_url: 用户微信头像远程访问地址
        :param nickname: 用户昵称
        :param code:二维码图片
        :return: 报告结果保存在服务器上的地址
        """
        if not os.path.exists(base_img_url):
            raise Exception('底图不存在')
        image = Image.open(base_img_url)
        # 将nickname绘画到指定区域
        font_path = os.path.abspath(os.path.join(MEDIA_ROOT, "fonts/PINGFANG REGULAR.TTF"))
        font = ImageFont.truetype(font_path, 28)
        draw = ImageDraw.Draw(image)
        draw.text((370, 100), nickname, fill=(0, 0, 0), font=font)
        # 将分享码绘画到指定区域
        font_path_bold = os.path.abspath(os.path.join(MEDIA_ROOT, "fonts/jiacu.ttf"))
        font = ImageFont.truetype(font_path_bold, 27)
        draw.text((491, 971), code, fill=(0, 0, 0), font=font)
        # 对远程获取的头像进行处理
        html_res = requests.get(head_img_url, verify=False)
        local_head_image = Image.open(BytesIO(html_res.content))
        local_head_image.thumbnail((90, 90))
        result = ImageProcessing.draw_circle_avatar(local_head_image, image, (270, 70))
        relative_path = 'images/result/' + str(uuid.uuid4()) + '.jpg'
        if not os.path.isdir(os.path.abspath(os.path.join(MEDIA_ROOT, 'images/result/'))):
            os.makedirs(os.path.abspath(os.path.join(MEDIA_ROOT, 'images/result/')))
        image_save_url = os.path.abspath(os.path.join(MEDIA_ROOT, relative_path))
        result.save(image_save_url)
        return relative_path

    @staticmethod
    def draw_circle_avatar(head_image, background, location):
        """
        将头像变成圆形绘制在背景图片上，然后将合成的图片对象返回
        """
        # 如果头像的色彩度是L，则需要进行转换，否则粘贴图片报异常
        if head_image.mode == 'L' or head_image.mode == 'CMYK':
            head_image = head_image.convert('RGB')
        big_size = (head_image.size[0] * 3, head_image.size[1] * 3)
        # 遮罩对象
        mask = Image.new('L', big_size, 0)
        draw = ImageDraw.Draw(mask)
        # 画椭圆的方法
        draw.ellipse((0, 0) + big_size, fill=600)
        # draw.rectangle((0, 0)+ big_size, fill=600)

        mask = mask.resize(head_image.size, Image.CUBIC)
        head_image.putalpha(mask)
        background.paste(head_image, location, mask)
        return background

    @staticmethod
    def draw_rectangle_avatar(head_image, background, location):
        """
        将头像变成圆形绘制在背景图片上，然后将合成的图片对象返回
        """
        # 如果头像的色彩度是L，则需要进行转换，否则粘贴图片报异常
        if head_image.mode == 'L' or head_image.mode == 'CMYK':
            head_image = head_image.convert('RGB')
        big_size = (head_image.size[0] * 3, head_image.size[1] * 3)
        # 遮罩对象
        mask = Image.new('L', big_size, 0)
        draw = ImageDraw.Draw(mask)
        # 画椭圆的方法
        # draw.ellipse((0, 0) + big_size, fill=600)
        draw.rectangle((0, 0) + big_size, fill=600)

        mask = mask.resize(head_image.size, Image.CUBIC)
        head_image.putalpha(mask)
        background.paste(head_image, location, mask)
        return background
